package com.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bhudy.base.BaseServiceImpl;
import com.bhudy.base.QueryFilter;
import com.sys.entity.SysMessage;
import com.sys.entity.SysMessageRecord;
import com.sys.entity.SysUser;
import com.sys.service.SysMessageService;
import com.sys.service.SysUserService;
import com.sys.utils.MailUtils;
import com.sys.utils.Utils;
import com.sys.utils.WeChatUtils;
import com.sys.websocket.SysWebSocketServer;
import com.bhudy.utils.XqhUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * @Author 卞洪业
 * @Description SysMessageService
 * @Date Tue Nov 12 10:57:04 CST 2019
 */
@Service
@Transactional
public class SysMessageServiceImpl extends BaseServiceImpl<SysMessage, Serializable> implements SysMessageService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public void sendSysMessage(SysMessage sysMessage) {
        QueryFilter queryFilter = new QueryFilter();

        Set<Long> userIdList = new HashSet<>();
        // 收信人类型（0全部，1角色，2用户）
        if (sysMessage.getReceiveType() == 0) {
            queryFilter.clear().and("status", 0);
            List<SysUser> sysUserList = sysUserService.findList(queryFilter);
            if (Utils.isBlank(sysUserList)) {
                for (SysUser sysUser : sysUserList) {
                    userIdList.add(sysUser.getUserId());
                }
            }
        } else if (sysMessage.getReceiveType() == 1) {
            queryFilter.clear().sql("where user_id in (select user_id from sys_user_role where role_id = ?)", sysMessage.getReceiveId());
            queryFilter.and("status", 0);
            List<SysUser> sysUserList = sysUserService.findList(queryFilter);
            if (Utils.isBlank(sysUserList)) {
                for (SysUser sysUser : sysUserList) {
                    userIdList.add(sysUser.getUserId());
                }
            }
        } else {
            userIdList.add(sysMessage.getReceiveId());
        }

        List<SysMessageRecord> sysMessageRecordList = new ArrayList<>();
        for (Long userId : userIdList) {
            SysMessageRecord sysMessageRecord = new SysMessageRecord();
            sysMessageRecord.setId(XqhUtils.createId());
            sysMessageRecord.setSysMessageId(sysMessage.getId());
            sysMessageRecord.setReceiveUserId(userId);
            sysMessageRecord.setReadStatus(0);
            sysMessageRecord.setMailReadStatus(0);
            sysMessageRecordList.add(sysMessageRecord);
        }


        for (SysMessageRecord sysMessageRecord : sysMessageRecordList) {
            this.sendSysMessage(sysMessage, sysMessageRecord);
        }
        super.insert(sysMessageRecordList);
    }

    @Override
    public void sendSysMessage(SysMessage sysMessage, SysMessageRecord sysMessageRecord) {
        SysUser sysUser = sysUserService.get(sysMessageRecord.getReceiveUserId());
        try {
            if (sysMessage.getNotifyTypes().matches(".*邮.*") && sysMessageRecord.getMailReadStatus().equals(0)) {
                if (sysMessage.getMailContent() != null && !sysMessage.getMailContent().equals("")) {
                    Map<String, Object> messageDataMap = JSONObject.parseObject(sysMessage.getMailContent(), Map.class);
                    MailUtils.send(sysMessageRecord.getReceiveUserId(), String.valueOf(messageDataMap.get("title")), String.valueOf(messageDataMap.get("content")));
                }
                sysMessageRecord.setMailReadStatus(2);
            }
        } catch (Exception e) {
            Utils.loggerError(this, e);
            sysMessageRecord.setMailReadStatus(0);
        }
        try {
            if (sysMessage.getNotifyTypes().matches(".*PC.*")) {
                if (sysMessage.getPcContent() != null && !sysMessage.getPcContent().equals("")) {
                    Map<String, Object> messageDataMap = JSONObject.parseObject(sysMessage.getPcContent(), Map.class);
                    SysWebSocketServer.send(sysMessageRecord.getReceiveUserId(), messageDataMap);
                }
            }
        } catch (Exception e) {
            Utils.loggerError(this, e);
        }
        try {
            if (sysMessage.getNotifyTypes().matches(".*短.*")) {

            }
        } catch (Exception e) {
            Utils.loggerError(this, e);
        }
        try {
            if (sysUser.getTasOpenid() != null && !sysUser.getTasOpenid().equals("") && sysMessage.getNotifyTypes().matches(".*微.*") && sysMessageRecord.getReadStatus().equals(0)) {
                if (sysMessage.getType() == 1) {
                    // 发送工单
                    if (sysMessage.getWechatTas() != null && !sysMessage.getWechatTas().equals("")) {
                        Map<String, Object> messageDataMap = JSONObject.parseObject(sysMessage.getWechatTas(), Map.class);
                        WeChatUtils.sendTasWorkOrder(sysUser.getTasOpenid(), messageDataMap);
                    }
                } else if (sysMessage.getType() == 2) {
                    // 产品价格变更
                    if (sysMessage.getWechatTas() != null && !sysMessage.getWechatTas().equals("")) {
                        Map<String, Object> messageDataMap = JSONObject.parseObject(sysMessage.getWechatTas(), Map.class);
                        WeChatUtils.sendTasProduct(sysUser.getTasOpenid(), messageDataMap);
                    }
                } else if (sysMessage.getType() == 3) {
                    // 产品库存变更
                    if (sysMessage.getWechatTas() != null && !sysMessage.getWechatTas().equals("")) {
                        Map<String, Object> messageDataMap = JSONObject.parseObject(sysMessage.getWechatTas(), Map.class);
                        WeChatUtils.sendTasProduct(sysUser.getTasOpenid(), messageDataMap);
                    }
                } else if (sysMessage.getType() == 4) {
                    // 缺货工单库存补充
                    if (sysMessage.getWechatTas() != null && !sysMessage.getWechatTas().equals("")) {
                        Map<String, Object> messageDataMap = JSONObject.parseObject(sysMessage.getWechatTas(), Map.class);
                        WeChatUtils.sendTasWorkOrder(sysUser.getTasOpenid(), messageDataMap);
                    }
                } else if (sysMessage.getType() == 5) {
                    // 工单进度通知
                    if (sysMessage.getWechatTas() != null && !sysMessage.getWechatTas().equals("")) {
                        Map<String, Object> messageDataMap = JSONObject.parseObject(sysMessage.getWechatTas(), Map.class);
                        WeChatUtils.sendTasOrderRateOfProgress(sysUser.getTasOpenid(), messageDataMap);
                    }
                }
                sysMessageRecord.setReadStatus(2);
            }
        } catch (Exception e) {
            Utils.loggerError(this, e);
            sysMessageRecord.setReadStatus(0);
        }
    }

    private String getPriorityStr(Integer priority) {
        switch (priority) {
            case 1:
                return "低";
            case 2:
                return "中";
            case 3:
                return "高";
            default:
                return "无";
        }
    }

    private String getStageStr(Integer stage, Integer orderStatus) {
        String key = stage + "_" + orderStatus;
        switch (key) {
            case "1_1":
                return "新建中";
            case "1_2":
                return "审核不通过";
            case "1_3":
                return "接单拒接";
            case "2_1":
                return "待审核";
            case "3_1":
                return "待接单";
            case "3_2":
                return "待处理";
            case "3_3":
                return "审计不通过";
            case "4_1":
                return "待审计";
            case "5_1":
                return "待结单";
            case "5_2":
                return "结单";
            default:
                return "未知";
        }
    }

}
